package com.yk.system.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yk.api.system.dto.CardDTO;
import com.yk.common.core.constant.NumberConstant;
import com.yk.common.core.domain.BasePageQuery;
import com.yk.common.core.domain.PageResult;
import com.yk.common.core.domain.Result;
import com.yk.common.core.utils.LoginHelper;
import com.yk.system.convert.CardConvert;
import com.yk.system.entity.Card;
import com.yk.system.entity.Gateway;
import com.yk.system.service.CardService;
import com.yk.system.service.GatewayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 流量卡管理
 *
 * @author lmx
 * @since 2024-02-20
 */
@Api(tags = "流量卡管理")
@RestController
@RequestMapping("/card")
@RequiredArgsConstructor
public class CardController {

    private final CardService cardService;
    private final GatewayService gatewayService;
    private final CardConvert cardConvert;

    @GetMapping("/getById/{id}")
    @ApiOperation("流量卡信息表-查询单个")
    public Result<Card> getById(@PathVariable(value = "id") Long id) {
        return Result.data(cardService.getById(id));
    }

    @PostMapping("/save")
    @ApiOperation("流量卡信息表-新增")
    public Result<Boolean> save(@RequestBody @Validated CardDTO dto) {
        return Result.data(cardService.save(cardConvert.dto2Entity(dto)));
    }

    @PostMapping("/batchSave")
    @ApiOperation("流量卡信息表-批量新增")
    public Result<Boolean> batchSave(@RequestBody @Validated CardDTO dto) {
        List<String> cardnoList = dto.getCardnoList();
        if (CollUtil.isEmpty(cardnoList)){
            return Result.fail("无数据可添加");
        }
        cardnoList.forEach(it -> {
            cardService.saveCard(it, NumberConstant.ZERO_STR);
        });
        return Result.ok();
    }

    @PostMapping("/batchUpdateAlarm")
    @ApiOperation("流量卡信息表-批量设置流量报警数值")
    public Result<Boolean> batchUpdateAlarm(@RequestBody @Validated CardDTO dto) {
        String alarm = dto.getAlarm();
        Assert.notBlank(alarm, "流量报警数值不能为空");
        List<Long> ids = dto.getIds();
        Assert.notEmpty(ids, "勾选数量不能为空");
        ids.forEach(it -> {
            Card card = cardService.getById(it);
            card.setAlarm(alarm);
            cardService.updateById(card);
        });
        return Result.ok();
    }

    @PostMapping("/update")
    @ApiOperation("流量卡信息表-修改")
    public Result<Boolean> updateById(@RequestBody @Validated CardDTO dto) {
        return Result.data(cardService.updateById(cardConvert.dto2Entity(dto)));
    }

    @GetMapping("/deleteById/{id}")
    @ApiOperation("流量卡信息表-删除")
    public Result<Boolean> deleteById(@PathVariable(value = "id") Long id) {
        return Result.data(cardService.removeById(id));
    }

    @PostMapping("/list")
    @ApiOperation("流量卡信息表-查询列表")
    public Result<List<Card>> list(@RequestBody CardDTO param) {
        final LambdaQueryWrapper<Card> lambda = new QueryWrapper<Card>().lambda();
        this.buildCondition(lambda, param);
        return Result.data(cardService.list(lambda));
    }

    @PostMapping("/page")
    @ApiOperation("流量卡信息表-分页查询")
    public PageResult<CardDTO> page(@RequestBody BasePageQuery<CardDTO> pageParam) {
        final CardDTO param = pageParam.getParam();
        LambdaQueryWrapper<Card> lambda = new QueryWrapper<Card>().lambda();
        buildCondition(lambda, param);
        lambda.eq(Card::getType, NumberConstant.ZERO_STR);
        if (StrUtil.isNotEmpty(param.getGateWayNumber())){
            List<Gateway> list = gatewayService
                    .list(new LambdaQueryWrapper<Gateway>().in(Gateway::getName, param.getGateWayNumber()));
            if (CollUtil.isNotEmpty(list)) {
                lambda.in(Card::getCardno, list.stream().map(Gateway::getCardNumber).collect(Collectors.toList()));
            }
        }
        IPage<CardDTO> page = cardService.page(new Page<>(pageParam.getPageNum(), pageParam.getPageSize()), lambda)
                .convert(cardConvert::entity2Dto);
        if (CollUtil.isNotEmpty(page.getRecords())) {
            page.getRecords().forEach(it -> {
                String cardno = it.getCardno();
                LambdaQueryWrapper<Gateway> assLambda = new LambdaQueryWrapper<>();
                assLambda.eq(Gateway::getCardNumber, cardno);
                List<Gateway> list = gatewayService.list(assLambda);
                if (CollUtil.isNotEmpty(list)) {
                    List<String> numberList = list.stream().map(Gateway::getNumber).collect(Collectors.toList());
                    String number = String.join(",", numberList);
                    it.setGateWayNumber(number);
                }
            });
        }
        return PageResult.success(page.getRecords(), page.getTotal());
    }

    @PostMapping("/pageByUser")
    @ApiOperation("客户端-流量卡信息表-分页查询")
    public PageResult<CardDTO> pageByUser(@RequestBody BasePageQuery<CardDTO> pageParam) {
        Long userId = LoginHelper.getLoginUserId();
        List<Gateway> list = gatewayService.list(new LambdaQueryWrapper<Gateway>().eq(Gateway::getCreatedBy, userId));
        if (CollUtil.isEmpty(list)) {
            return PageResult.success(CollUtil.newArrayList(), 0);
        }
        List<String> ccIdList = list.stream().map(Gateway::getCardNumber).collect(Collectors.toList());
        CardDTO param = pageParam.getParam();
        LambdaQueryWrapper<Card> lambda = new QueryWrapper<Card>().lambda();
        lambda.in(Card::getCardno, ccIdList);
        this.buildCondition(lambda, param);
        IPage<CardDTO> page = cardService.page(new Page<>(pageParam.getPageNum(), pageParam.getPageSize()), lambda)
                .convert(cardConvert::entity2Dto);
        if (CollUtil.isNotEmpty(page.getRecords())) {
            page.getRecords().forEach(it -> {
                String cardno = it.getCardno();
                LambdaQueryWrapper<Gateway> gateLambda = new LambdaQueryWrapper<>();
                gateLambda.eq(Gateway::getCardNumber, cardno);
                gateLambda.eq(Gateway::getCreatedBy, userId);
                List<Gateway> gatewayList = gatewayService.list(gateLambda);
                if (CollUtil.isNotEmpty(gatewayList)) {
                    List<String> nameList = gatewayList.stream().map(Gateway::getName).collect(Collectors.toList());
                    String gateName = String.join(",", nameList);
                    it.setGateWayName(gateName);
                }
            });
        }
        return PageResult.success(page.getRecords(), page.getTotal());
    }

    /**
     * 构造查询条件
     *
     * @param lambda
     * @param param
     */
    private void buildCondition(LambdaQueryWrapper<Card> lambda, CardDTO param) {
        lambda.eq(Objects.nonNull(param.getState()), Card::getState, param.getState());
        lambda.like(Objects.nonNull(param.getCardno()), Card::getCardno, param.getCardno());
        lambda.orderBy(true, false, Card::getId);
    }
}